// prefix for state keys of poll options
var OPTION_KEY_PREFIX = 'option:';
var data = {"count":0,"participants":[]};
var showVotersP = false;

// Report error message
// TODO: Use something nicer than alert
function errorMessage(messageText)
{
  //alert(messageText);
  $('#errorMessages').hide()
    .html('<div class="e">'+
        '<span>'+gadgets.util.escapeString(messageText)+
        '<span class="c"> (click to hide)</span></span></div>')
    .show('slow', function() {
      gadgets.window.adjustHeight();
    });
}

function setElementText(element, text) {
  element.innerHTML = '';
  element.appendChild( document.createTextNode( text ) );
}

/* Takes the name of a poll option and returns
  the key to use in the Wave state. */
function convertOptionToKey(optionName) {
  return OPTION_KEY_PREFIX+optionName;
}

/*
  Takes a state key and grabs the option name
  from it. If it isn't recognised as an option
  key, null is returned.
*/
function convertKeyToOption(stateKey) {
  if (typeof stateKey != 'undefined' && stateKey && stateKey.indexOf(OPTION_KEY_PREFIX) == 0) {
    return stateKey.substring(OPTION_KEY_PREFIX.length);
  }
  return null;
}

// called when gadget is ready
$(function(){
  $('#errorMessages').click(function(e){
    $(this).hide('slow', function() {
      $(this).html(''); //clear messages
      gadgets.window.adjustHeight();
    });
  });
});

  // called by Wave API after state changes
  function renderInfo(){
    var state = wave.getState();
    if(!state) return;

    renderPoll(state); // Needs to be defined elsewhere

    gadgets.window.adjustHeight();
  }

  // convenience function for creating an element with a bunch of simple attributes
  function newElement(name, attributes) {
    var el = document.createElement(name);
    for (n in attributes) {
      el[n] = attributes[n];
    }
    return el;
  }

  function renderTable(state, PollItemClass){
    var pollTable = document.getElementById("pollResults");
    pollTable.innerHTML = '';

    // loop through gathered data to generate view

      var pollItem = new PollItemClass(data);
      var name = "score";

      var button = pollItem.getVoteButton();
      var votes = pollItem.getNumVotes();
      var votesWidth = votes;

      var mood;
      if(votesWidth>66) mood = "high";
      else if(votesWidth>33) mood = "medium";
      else mood="low";

      var filled = document.createElement("div");
      filled.className = 'optionValueFill ' + mood;
      filled.style.width = votesWidth + '%';

      var votesDiv = newElement("div", { className:'votes_div' });
      //filled.appendChild(label);
      votesDiv.appendChild(filled);

      var tr = newElement('tr', { className: 'optionRow' });

      var showVoters = newElement('a', {
        innerHTML:'show', href:'#', className:'showVoters', title:'show voters',
        onclick: function(){
                 if (showVotersP == true) {
                     showVotersP = false; }
                 else showVotersP = true;
                 renderInfo(); }
      });

      var td = newElement("td", { className:'optionLabel' });
      setElementText(td, votes + " votes -- ");
      td.appendChild(showVoters);
      // td.appendChild(label);
      tr.appendChild(td);

      td = newElement("td", { className:'optionValue' });
      td.appendChild(votesDiv);
      tr.appendChild(td);

      td = newElement("td", { className:'optionButton' });
      if(button) td.appendChild(button);
      tr.appendChild(td);

      pollTable.appendChild(tr);

      if(votes > 0 && showVotersP)
      {
        tr = newElement('tr', { className: 'optionRow' });
        tr.appendChild( newElement('td') );

        td = newElement('td');

        var voters = pollItem.getVoters();
        $(voters).each(function(i,p){
            var img = newElement('img',
                    { src: p.getThumbnailUrl(),
                      alt: p.getDisplayName(),
                      title: p.getDisplayName(),
                      className: 'thumbnail' } );
            td.appendChild(img);

            //var votesCount = createTextNode(p.get);
            //td.appendChild(votesCount);
        });

        tr.appendChild(td);
        tr.appendChild( newElement('td') );
        pollTable.appendChild(tr);
      }
  }

  function getStateValue(key) {
    var value = wave.getState().get(key);
    if(value) {
      try {
        return gadgets.json.parse(value);
      } catch(e) {
        return null;
      }
    }
  }

  /** save value as top level state. stringifies JSON objects. */
  function submitValue(key, value) {
    var delta = {};
    value = gadgets.json.stringify(value);
    delta[key] = value;
    wave.getState().submitDelta(delta);
  }

    /**
     * Called when Gadget is loaded.
     * Registers function renderInfo which will be called
     * when ever a state is changed or a participant added
     */
  function init() {
    if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(renderInfo);
      wave.setParticipantCallback(renderInfo);
      wave.log('Starting up poll gadget');
    }

    showInput();
  }

  function setVisible(id, visible) {
    el = document.getElementById(id);
    if(el) {
      el.style.display = (visible ? "block" : "none");
    }
  }

  function showInput() {
    // setVisible(name, show);
    // setVisible("edit_poll", true);

    gadgets.window.adjustHeight();
  }

  gadgets.util.registerOnLoadHandler(init);